//
//  CQPictureCell.m
//  Pods
//
//  Created by 陈长青 on 2017/4/4.
//
//

#import "CQPictureCell.h"
#import <YYWebImage/YYWebImage.h>
#import "NSTimer+Additions.h"
#import "CQVBNavigationBar.h"
#import "CQVideoCell.h"

@interface CQPictureCell ()<UIScrollViewDelegate>

// 图片控件

@property (nonatomic, weak) UIImageView *imageView;

// 图片控件高度约束

@property (nonatomic, weak) NSLayoutConstraint *imageViewWHRadio;

// 图片控件上边距

@property (nonatomic, weak) NSLayoutConstraint *imageViewTop;

// 图片控件左边距

@property (nonatomic, weak) NSLayoutConstraint *imageViewLeft;

// 图片控件右边距

@property (nonatomic, weak) NSLayoutConstraint *imageViewRight;

// 图片控件下边距

@property (nonatomic, weak) NSLayoutConstraint *imageViewBottom;

// 图片控件宽

@property (nonatomic, weak) NSLayoutConstraint *imageViewWidth;

// 图片控件高

@property (nonatomic, weak) NSLayoutConstraint *imageViewHeight;

// 图片空间centerX

@property (nonatomic, weak) NSLayoutConstraint *imageViewCenterX;

// 显示文字

@property (weak, nonatomic) UILabel *textLabel;

// 图片大小

@property (assign, nonatomic) CGSize pictureSize;

// cell大小

@property (assign, nonatomic) CGSize cellSize;

// 远程图片

@property (nonatomic, strong) NSString *remoteUrl;

// 占位图

@property (nonatomic, strong) UIImage *placeHolder;

// 是否显示导航栏、底栏

@property (nonatomic) BOOL controlsHidden;

// 计时器

@property (strong, nonatomic) NSTimer *timer;

// 导航栏、底栏集合

@property (strong, nonatomic) NSMutableArray *excludedViews;

// 最后一次屏幕方向

@property (assign, nonatomic) BOOL isVertical;

@end

@implementation CQPictureCell
@synthesize reuseIdentifier=_reuseIdentifier;
@synthesize textLabel=_textLabel;
@synthesize index=_index;
@synthesize toolBar=_toolBar;
@synthesize navigationBar=_navigationBar;
@synthesize contentView=_contentView;

#pragma mark - 生命周期

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
    self = [self initWithFrame:CGRectZero];
    if (self) {
        
        _reuseIdentifier = reuseIdentifier;
        _controlsHidden = YES;
        _isVertical = YES;
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    
    self.delegate = self;
    self.alwaysBounceVertical = true;
    self.backgroundColor = [UIColor blackColor];
    self.showsHorizontalScrollIndicator = false;
    self.showsVerticalScrollIndicator = false;
    self.maximumZoomScale = 2;
    
    // 添加 imageView
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.clipsToBounds = true;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.userInteractionEnabled = true;
    imageView.backgroundColor = [UIColor grayColor];
    [self addSubview:imageView];
    _imageView = imageView;
    
    // 注册通知监听者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
// 处理旋转过程中需要的操作

- (void)orientationChanged:(NSNotification *)note  {
    
    [self setPictureSize:_pictureSize andCellSize:_cellSize];
}

- (void)dealloc {
    
    [_toolBar removeFromSuperview];
    _toolBar = nil;
    
    [_navigationBar removeFromSuperview];
    _navigationBar = nil;
    
    [_imageView yy_cancelCurrentImageRequest];
    [_timer invalidate];
    _timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"%s",__FUNCTION__);
}

#pragma mark - 外部方法

- (void)setPictureSize:(CGSize)pictureSize andCellSize:(CGSize)cellSize {
    
    _pictureSize = pictureSize;
    _cellSize = cellSize;
    
    UIDeviceOrientation o = [[UIDevice currentDevice] orientation];
    switch (o) {
        case UIDeviceOrientationPortrait:            // Device oriented vertically, home button on the bottom
            _isVertical = YES;
            [self fitVertical];
            break;
        case UIDeviceOrientationPortraitUpsideDown:  // Device oriented vertically, home button on the top
            
            break;
        case UIDeviceOrientationLandscapeLeft:      // Device oriented horizontally, home button on the right
            _isVertical = NO;
            [self fitHorizontal];
            break;
        case UIDeviceOrientationLandscapeRight:      // Device oriented horizontally, home button on the left
            _isVertical = NO;
            [self fitHorizontal];
            break;
        default:
            
            break;
    }
//    [self fitVertical];
    
}

// 下载图片

- (void)setRemoteUrl:(NSString *)remoteUrl andPlaceHolder:(UIImage *)placeHolder {
    _remoteUrl = remoteUrl;
    _placeHolder = placeHolder;
    
    [self.imageView yy_cancelCurrentImageRequest];
    
    // 取消上一次的下载
    __weak typeof(self) weakSelf = self;
    [self.imageView yy_setImageWithURL:[NSURL URLWithString:remoteUrl] placeholder:_placeHolder options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//        CGFloat progress = (CGFloat)receivedSize / expectedSize ;
        
    } transform:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        if (error != nil) {
            
        }else {
            if (stage == YYWebImageStageFinished) {
                
                if (image != nil) {
                    
                    [weakSelf setPictureSize:image.size andCellSize:self->_cellSize];
                    
                    if (![self isKindOfClass:[CQVideoCell class]]) {
                        
                        if ([weakSelf.navigationBar isKindOfClass:[CQVBNavigationBar class]]) {
                            
                            CQVBNavigationBar *nav = (CQVBNavigationBar *)weakSelf.navigationBar;
                            nav.isShowDownloadBtn = YES;
                        }
                    }
                }else {
                    
                }
            }
        }
    }];
}

// 本地图片

- (void)setLocalImage:(UIImage *)localImage {
    _localImage = localImage;
    
    self.imageView.image = localImage;
    
    [self setPictureSize:localImage.size andCellSize:_cellSize];
    
    if (![self isKindOfClass:[CQVideoCell class]]) {
        
        if ([self.navigationBar isKindOfClass:[CQVBNavigationBar class]]) {
            
            CQVBNavigationBar *nav = (CQVBNavigationBar *)self.navigationBar;
            nav.isShowDownloadBtn = YES;
        }
    }
}

#pragma mark - 自适应

// 清空约束

- (void)clearConstraints {
    
    if (_imageViewWHRadio) {
        [_imageView removeConstraint:_imageViewWHRadio];
    }
    
    if (_imageViewTop) {
        [self removeConstraint:_imageViewTop];
    }
    
    if (_imageViewLeft) {
        [self removeConstraint:_imageViewLeft];
    }
    
    if (_imageViewRight) {
        [self removeConstraint:_imageViewRight];
    }
    
    if (_imageViewBottom) {
        [self removeConstraint:_imageViewBottom];
    }
    
    if (_imageViewWidth) {
        
        [_imageView removeConstraint:_imageViewWidth];
    }
    
    if (_imageViewHeight) {
        
        [_imageView removeConstraint:_imageViewHeight];
    }
    if (_imageViewCenterX) {
        
        [self removeConstraint:_imageViewCenterX];
    }
}

// 适应横屏

- (void)fitHorizontal {
    
    _imageView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self clearConstraints];
    
    // 计算图片的显示宽度
    CGFloat pictureShowSizeW = _cellSize.width * _pictureSize.width/ _pictureSize.height;
    
    NSLayoutConstraint *imageViewTop = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1 constant:0];
    [self addConstraint:imageViewTop];
    _imageViewTop = imageViewTop;
    
    NSLayoutConstraint *imageViewBottom = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
    [self addConstraint:imageViewBottom];
    _imageViewBottom = imageViewBottom;
    
    NSLayoutConstraint *imageViewWidth = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1 constant:pictureShowSizeW];
    [_imageView addConstraint: imageViewWidth];
    _imageViewWidth = imageViewWidth;
    
    NSLayoutConstraint *imageViewCenterX = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    [self addConstraint:imageViewCenterX];
    _imageViewCenterX = imageViewCenterX;

    [self addImageViewWHRadio:_pictureSize.width/_pictureSize.height];
}

// 适应竖屏

- (void)fitVertical {
    
    _imageView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self clearConstraints];
    
    // 计算图片的显示宽度
    CGFloat pictureShowSizeH =  _cellSize.width * _pictureSize.height/ _pictureSize.width;
    
    CGFloat top = pictureShowSizeH > _cellSize.height ? 0 : (_cellSize.height - pictureShowSizeH)/2;
    
    NSLayoutConstraint *imageViewTop = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1 constant:top];
    [self addConstraint:imageViewTop];
    _imageViewTop = imageViewTop;
        
    NSLayoutConstraint *imageViewBottom = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
    [self addConstraint:imageViewBottom];
    _imageViewBottom = imageViewBottom;

    NSLayoutConstraint *imageViewWidth = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1 constant:_cellSize.width];
    [_imageView addConstraint: imageViewWidth];
    _imageViewWidth = imageViewWidth;
    
    NSLayoutConstraint *imageViewHeight = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1 constant:pictureShowSizeH];
    [_imageView addConstraint: imageViewHeight];
    _imageViewHeight = imageViewHeight;
    
    NSLayoutConstraint *imageViewCenterX = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    [self addConstraint:imageViewCenterX];
    _imageViewCenterX = imageViewCenterX;

    [self addImageViewWHRadio:_pictureSize.width/_pictureSize.height];
}

#pragma mark - 私有方法

- (void)setNavigationBar:(UIView<CQNavigationBarProtocol> *)navigationBar {
    [_navigationBar removeFromSuperview];
    _navigationBar = navigationBar;
    _navigationBar.cell = self;
}

- (void)setToolBar:(UIView<CQToolBarProtocol> *)toolBar {
    [_toolBar removeFromSuperview];
    _toolBar = toolBar;
    _toolBar.cell = self;
}

- (void)setContentView:(UIView<CQContentViewProtocol> *)contentView {
    [_contentView removeFromSuperview];
    _contentView = contentView;
    _contentView.cell = self;
}

- (void)addImageViewWHRadio:(CGFloat)multiplier {
    
    if (_imageViewWHRadio) {
        
        [_imageView removeConstraint:_imageViewWHRadio];
    }
    
    NSLayoutConstraint *imageViewWHRadio = [NSLayoutConstraint constraintWithItem:_imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_imageView attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
    [_imageView addConstraint:imageViewWHRadio];
    _imageViewWHRadio = imageViewWHRadio;
}

- (UILabel *)textLabel {
    
    if (!_textLabel) {
        
        UILabel *textLabel = [UILabel new];
        textLabel.textAlignment = NSTextAlignmentCenter;
        textLabel.font = [UIFont systemFontOfSize:12];
        textLabel.textColor = [UIColor redColor];
        [self addSubview:textLabel];
        _textLabel = textLabel;
        
        _textLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self addConstraint:[NSLayoutConstraint constraintWithItem:_textLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:_textLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
        
    }
    return _textLabel;
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return _imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGPoint center = _imageView.center;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height) ? (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    center.y = scrollView.contentSize.height * 0.5 + offsetY;
    _imageView.center = center;
    
    // 如果是缩小，保证在屏幕中间
    if (scrollView.zoomScale < scrollView.minimumZoomScale) {
        CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width) ? (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
        center.x = scrollView.contentSize.width * 0.5 + offsetX;
        _imageView.center = center;
    }
}

@end
